#!/usr/bin/perl
##################################################################################
# Copyright (C) 2010  Chris Rutledge <rutledge.chris@gmail.com>
#
# http://code.google.com/p/apsh
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
##################################################################################
use strict;
use lib "/usr/local/lib/perl";
use APSH;

my %OUTPUT   = ();
my @C_OUTPUT = ();

my $NODEGROUPS = APSH::GetNodeGroups();

while (<STDIN>){
   chomp($_);

   my ($node, $line) = split(/:/, $_, 2);

   $node =~ s/://g;
   $line =~ s/^\s+//;

   push(@{$OUTPUT{$node}}, "$line\n");
}

for my $KEY (keys %OUTPUT){
   my ($FLAG, $i) = undef;

   for $i (0 .. $#C_OUTPUT){
      if ("@{$C_OUTPUT[$i]{'OUTPUT'}}" eq "@{$OUTPUT{$KEY}}"){
         $FLAG  = "1";
         push(@{$C_OUTPUT[$i]{'HOSTS'}}, "$KEY");
      }
   }

   if (! $FLAG){
      $i = @C_OUTPUT;

      @{$C_OUTPUT[$i]{'OUTPUT'}} = @{$OUTPUT{$KEY}};

      push(@{$C_OUTPUT[$i]{'HOSTS'}}, "$KEY");
   }
}

for my $i (0 .. $#C_OUTPUT){
   my $NODES = main::GroupNodes(sort { lc($a) cmp lc($b) }@{$C_OUTPUT[$i]{'HOSTS'}});

   print "##########################################\n";
   print "$NODES\n";
   print "##########################################\n";

   for (@{$C_OUTPUT[$i]{'OUTPUT'}}){
      print $_;
   }

   print "\n\n";
}

sub GroupNodes{
   my $NODES = "@_";

   foreach my $KEY (sort { $NODEGROUPS->{$b}{'SIZE'} <=> $NODEGROUPS->{$a}{'SIZE'} } keys %$NODEGROUPS){
      if ($NODES =~ /$NODEGROUPS->{$KEY}{'NODES'}/){
         $NODES =~ s/$NODEGROUPS->{$KEY}{'NODES'}/$KEY/;
      }
   }

   return($NODES);
}
